<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 太阳2 ajie
 */
class Taiyang2Controller extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.ordNo") ? I("request.ordNo") : I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        // $isMobile = isMobile();
        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){
            //微信
            case 1:
            //微信H5
            case 2:
                $pay_bankcode = 'wxsp';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $native = array(
            "mer_no" => $this->config['mch_id'],
            "mer_user_no" => '000115000128000000000001' ,
            "trans_id" => $return['orderid'],
            "pay_time" => strval(getMillisecond())  ,
            "notify_url" => $return['notifyurl'],
            "front_url" =>$return['callbackurl'],
            "body" => 'wlf' ,
            "spbill_create_ip" => getIP(),
            "version" =>  '1.0.0' ,
            "sign_type" => 'RSA',
        );



        $data = array(
            "money" => intval($return['amount']*100),
            "pay_type" => $pay_bankcode ,
            "trade_type" => 'T1',
        );


        $native['data'] = $this->encryptByAes($data,$this->config['signkey']);//ase 加密

        $privateKey = 'MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEAnhWwuAOev9nO7xZ/aYzMzbA9XZEgzpYFyMAyTuRNANvmpNYm1Jp/wDyMPOrHyjwX6YyMWTWyP+H43iZiRPFZdwIDAQABAkEAgA5R+L31+rMVTdeLnpTP0k7RZtoJGU+tn9EQ75dASVCShrvPfqiz3avvbBLjISwWg7BpOYCwsyJOIe68UBGMAQIhANBR+oQh3thcj+bqqRiS+oMILVE97xhRk9xUlnkGQ5YnAiEAwkRIoBoBAQM7UblTDFJ+4fWNnamn6+2YoxM4vAmvBDECIEEa/dJBy6WO+CJRAFv/w28kJRWY55qQFEft38EfJgxNAiEAu1qphCawEy7vtah67KZfEkMEeiqV9VZm39d43vij3vECIQCkUcf7W4ovHjz7oN/yzfwGdgnFziWW37FIZ6TVnpfKkA==';

        $native['sign'] = $this->generateSign($native, $privateKey);

     //var_dump('<pre/>',$this->config['signkey'], $native['data'],$native,$this->config['gateway']);exit();
        po($this->config['gateway'],$native);

    }


    public function verifyRsaSign($params, $public_key)
    {
        if (is_null($public_key)) {
            throw new InvalidArgumentException('Missing dingding Config -- [key]');
        }

        $signStr = $this->getSignContent($params);


        $public_key = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($public_key, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";
        if (false == ($rsa_public_key = openssl_pkey_get_public($public_key))) {
            throw new InvalidArgumentException('public key error -- [key]' . openssl_error_string());
        }

        $return_sign = $params['sign'];
        $isVerify = openssl_verify($signStr, base64_decode($return_sign), $rsa_public_key, OPENSSL_ALGO_SHA1);
        return $isVerify === 1 ? true : false;
    }



    //通知
    public function notifyurl(){
        //$this->debug_callback();

        //IP白名单
        if(!$this->checkip(getIP(),['47.103.118.212'])){
            exit("wrong");
        }


        $p = I("post.");


        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['trans_id'];

        //获取订单
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
             "pay_orderid_rd"=>htmlspecialchars($p['order_id'])
        ));


        $real_amount =  $p['money']/100;     //实际支付金额
        $pay_amount =  $find['pay_amount']; //商户提交订单金额

        if(abs($real_amount - $pay_amount) > 1){
            echo 'wrong_money'; exit;
        }

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>$this->class]);


        $public = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnvsPhtfbKlqJwrX1x/H9/ggxnOqHGjpiNutkkyoFZcLcDioZrKZOjTyakkRbLqSYeX2Uhyx2eegLBAOvEycMsGjTR4yUtrvLe3yQxstjrrB5qemWqDK/9Pe5vP32PJU36BQdR+hY6Pc+OyZ1kCWXF+aItpF1YOfuw+oFCDy1Ug1ruGy2xzaHIR/agl7xDDHrWeyHLKpqbuosgSAlIGXbGkNID8g0Z08mGxpbTj3X+5M8geqx/+lpfownb+HmnBp4ephTnu9p67XkkxHiSsrPr+ncVH59uZn5/+/auY+W16i49PHZ4vnJD2IaADEXqvBr3OjiczWsVNNG0zo/V6u7rQIDAQAB';

        $res = $this->verifyRsaSign($p, $public);

        if($res){
            exit("sign_wrong");
        }

        if($p['status'] !== '1'){
            exit("fail");
        }


        $this->async($find['pay_orderid'],"allpay_success");
    }


    /**
     * AES-128-ecb加密
     * @param $data 加密字符
     * @param $key 密码
     * @return string
     */
    public  function encryptByAes($contents, $key)
    {
        if (is_null($key)) {
            exit('private_key null');
        }
        $text = \json_encode($contents);
        $encrypted = openssl_encrypt($text, 'aes-128-cbc', $key ,OPENSSL_RAW_DATA, 'alpayaesivvector');
        return base64_encode($encrypted);
    }


    /**
     * Generate wechat sign.
     *
     * @author Payment <me@Payment.cn>
     *
     * @param array $data
     * @param null|string $key
     *
     * @throws InvalidArgumentException
     *
     * @return string
     */
    public function generateSign($data, $private_key = null)
    {
        if (is_null($private_key)) {
            exit('private_key null');
        }
        $signStr = $this->getSignContent($data);

        $private_key = "-----BEGIN RSA PRIVATE KEY-----" . PHP_EOL .
            wordwrap($private_key, 64, "\n", true)
            . PHP_EOL . "-----END RSA PRIVATE KEY-----";

        $sign_info = '';

        //判断私钥文件是否可用
        $piKey = openssl_pkey_get_private($private_key);

        if ($piKey) {
            $res = openssl_get_privatekey($private_key);
            openssl_sign($signStr, $sign_info, $res);
            $sign_info = base64_encode($sign_info);
        }

        return $sign_info;
    }


    /**
     * Generate sign content.
     *
     * @author Payment <me@Payment.cn>
     *
     * @param array $data
     *
     * @return string
     */
    public function getSignContent($data)
    {
        $buff = '';
        ksort($data);
        foreach ($data as $k => $v) {
            $buff .= (!in_array($k, ['sign']) && $v !== '' && !is_array($v)) ? $k . '=' . $v . '&' : '';
        }

        //如果存在转义字符，那么去掉转义
        if (get_magic_quotes_gpc()) $buff = stripslashes($buff);

        return trim($buff, '&');
    }



    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
